package cn.tworice.blog.web;

import cn.tworice.blog.entity.ErrorInfo;
import cn.tworice.blog.service.ToolsService;
import cn.tworice.blog.utils.CoreService;
import com.alibaba.fastjson.JSON;
import com.lmk.core.web.support.api.RequestResult;
import com.lmk.core.web.support.api.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 错误信息处理
 * @author 二饭
 * @email 1786705138@qq.com
 */
@RestControllerAdvice
@Slf4j
public class ExceptionController {

    // 构造器注入
    final ToolsService toolsService;

    @Autowired
    public ExceptionController(ToolsService toolsService){
        this.toolsService=toolsService;
    }

    @ExceptionHandler(Exception.class)
    public RequestResult handleException(Exception exception, HttpServletRequest request) {
        exception.printStackTrace();

        // 异步存储错误信息
        new Thread(()->{
            ErrorInfo error=new ErrorInfo();
            error.setErrorInfo(exception.getMessage());
            error.setUserIp(CoreService.getIpAddress(request));
            error.setParams(JSON.toJSONString(request.getParameterMap()));
            error.setUri(request.getRequestURI());
            toolsService.saveErrorInfo(error);
        }).start();

        log.error("接口-"+request.getRequestURI()+"-返回错误代码500，服务器异常!");
        return new RequestResult(new StatusCode(500,"系统繁忙"));
    }
}